package com.zjc.gateway.exception;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zjc.gateway.constants.GenericResultDto;
import com.zjc.gateway.constants.AppExcCodesEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Order(-2)
@Configuration
public class CustomExceptionHandler implements ErrorWebExceptionHandler {

    private static Gson gson = new GsonBuilder().create();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        GenericResultDto resultDto;
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        if (ex instanceof NotFoundException) {
            resultDto = GenericResultDto.fail(AppExcCodesEnum.SERVICE_UNAVAILABLE.getCode(), ex.getMessage());
        } else if (ex instanceof ResponseStatusException) {
            resultDto = GenericResultDto.fail(AppExcCodesEnum.OPERATE_FAIL.getCode(), response.getStatusCode() + ":" + ex.getMessage());
        } else {
            resultDto = GenericResultDto.fail(AppExcCodesEnum.OPERATE_FAIL.getCode(), ex.getMessage());
        }
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage(), ex);

        return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, resultDto);

    }

    /**
     * 设置webflux模型响应
     *
     * @param response    ServerHttpResponse
     * @param contentType content-type
     * @param resultDto   响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, GenericResultDto resultDto) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        DataBuffer dataBuffer = response.bufferFactory().wrap(gson.toJson(resultDto).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
